﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal;

namespace SecurityAgentServiceWebControls
{
    public class SecurityAgentServiceModule : IHttpModule
    {
        #region Fields

        private const string UserTokenNameSetting = "UserToken";

        #endregion

        #region IHttpModule Members

        public void Dispose()
        { }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        private static void context_AuthenticateRequest(object sender, EventArgs e)
        {
            
            // Access the current Http application.
            HttpApplication application = sender as HttpApplication;
            if (application == null)
            {
                throw new InvalidOperationException("Http application cannot be null.");
            }

            // Get the HttpContext for the current request.
            HttpContext context = application.Context;
            if (context == null)
            {
                throw new InvalidOperationException("Http context cannot be null.");
            }

            // Read the application name stored in the FormsAuthenticationTicket
            string userToken = String.Empty;
            if (context.Request.IsAuthenticated)
            {
                FormsIdentity identity = context.User.Identity as FormsIdentity;
                if (identity != null)
                {
                    FormsAuthenticationTicket ticket = identity.Ticket;
                    if (ticket != null)
                    {
                        List<string> settings = new List<string>(ticket.UserData.Split(';'));
                        foreach (string s in settings)
                        {
                            string setting = s.Trim();
                            if (setting.StartsWith("SASTK="))
                            {
                                int startIndex = setting.IndexOf("SASTK=") + 6;
                                userToken = setting.Substring(startIndex);
                                break;
                            }
                        }

                    }

                    if (!String.IsNullOrEmpty(userToken))
                    {
                        SecurityAgent.SASIdentity newIdentity = new SecurityAgent.SASIdentity(identity, userToken);
                        context.User = new GenericPrincipal(newIdentity, null);     // will later be replaced by RoleManagerModule but the identity will carry on
                        System.Threading.Thread.CurrentPrincipal = context.User;    
                        
                    }
                }
            }

            // Store the application name in the Items collection of the per-request http context.
            // Storing it in the session state is not an option as the session is not available at this
            // time. It is only available when the Http application triggers the AcquireRequestState event.
            context.Items[UserTokenNameSetting] = userToken;


        }

        #endregion
    }
}
